//
//  MulitySettingViewController.m
//  wAudioShare
//
//  Created by Ning on 14-9-15.
//  Copyright (c) 2014年 赵帅. All rights reserved.
//

#import "MulitySettingViewController.h"
#import "CustomIOS7AlertView.h"
#import "Utitlity.h"
#import "MMProgressHUD.h"
#import "WISInterfaces.h"
#import "PersistableInfo.h"

@interface MulitySettingViewController ()<CustomIOS7AlertViewDelegate,UITextFieldDelegate,UIAlertViewDelegate,MBProgressHUDDelegate>{
    //chagne
    UIView *customAlertView;
    UITextField *oldPasswordTextField;
    UITextField *newPasswordTextField;
    UITextField *surePasswordTextField;
    //changeDeviceName
    UIView *changeNameAlertView;
    UITextField *changeNameTextField;
    
    //reset
    UIView *resetAlertView;
    UITextField *userNameTextField;
    UITextField *passWordTextField;
    
    NSString *ipUrl;
    BottomView *bottomView;
    
    NSString *oldDeviceName; //设备老名字
}
@property (weak, nonatomic) IBOutlet UIButton *changName;
@property (weak, nonatomic) IBOutlet UIButton *changPassword;
@property (weak, nonatomic) IBOutlet UIButton *changStreet;
@property (weak, nonatomic) IBOutlet UIButton *resetChuChang;
@property (weak, nonatomic) IBOutlet UIButton *reOpen;

@end

@implementation MulitySettingViewController
@synthesize value;
@synthesize delegate;

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self.changName addTarget:self action:@selector(changNameTouch) forControlEvents:UIControlEventTouchUpInside];
    [self.changPassword addTarget:self action:@selector(changePasswordTouch) forControlEvents:UIControlEventTouchUpInside];
    [self.changStreet addTarget:self action:@selector(changeStreetTouch) forControlEvents:UIControlEventTouchUpInside];
    [self.resetChuChang addTarget:self action:@selector(resetChuChangeTouch) forControlEvents:UIControlEventTouchUpInside];
    [self.reOpen addTarget:self action:@selector(reOpenTouch) forControlEvents:UIControlEventTouchUpInside];
    
    bottomView = [self addBottomView];
    
    wis_user_dev device;
    [value getValue:&device];
    oldDeviceName = [NSString stringWithUTF8String:device.name];

    // Do any additional setup after loading the view from its nib.
    
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(textFiledEditChanged:)
                                                name:@"UITextFieldTextDidChangeNotification"
                                              object:changeNameTextField];

}

//修改名字
- (void)changNameTouch
{
    CustomIOS7AlertView *alertView = [[CustomIOS7AlertView alloc] init];
    alertView.delegate = self;
    alertView.tag = 20000;
    [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"取消",@"确定", nil]];//添加按钮
    [alertView setContainerView:[self changeDeviceNameView:changeNameAlertView]];
    [alertView show];
}

//修改密码
- (void)changePasswordTouch
{
    CustomIOS7AlertView *alertView = [[CustomIOS7AlertView alloc] init];
    alertView.delegate = self;
    alertView.tag = 10000;
    [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"取消",@"确定", nil]];//添加按钮
    [alertView setContainerView:[self initializeAlertView:customAlertView]];
    [alertView show];
}

//路径重组
- (void)changeStreetTouch
{
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        NSString *string = [NSString stringWithFormat:@"http://%@/cgi-bin/HealNetwork.cgi?ZID=255&doRR=0",ipUrl];
        NSLog(@"changeString:%@",string);
        
        [Utitlity commonHTTPMethod:string responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"changeStreetTouch:%@",responseObject);
            if([responseObject[@"state"] isEqualToString:@"Success"])
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"发送成功" message:@"路径重组大概需要20分钟，请稍后....." delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil];
                [alert show];
            }else{
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"发送失败" message:@"设备繁忙，请稍后在试....." delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil];
                [alert show];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
        
    }
}

// 恢复出厂设置
- (void)resetChuChangeTouch
{
    CustomIOS7AlertView *alertView = [[CustomIOS7AlertView alloc] init];
    alertView.delegate = self;
    alertView.tag = 40000;
    [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"取消",@"确定", nil]];//添加按钮
    [alertView setContainerView:[self reSetView:resetAlertView]];
    [alertView show];
}

//重启设备
- (void)reOpenTouch
{

    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        NSString *reOpenStr = [NSString stringWithFormat:@"http://%@/cgi-bin/User.cgi?action=do_reboot&seconds=0",ipUrl];
        
        [Utitlity commonHTTPMethod:reOpenStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            NSLog(@"reOpenStr:%@",responseObject);
            if ([responseObject[@"state"] isEqualToString:@"Success"])
            {
                [MMProgressHUD showWithStatus:@"设备重新启动...."];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [MMProgressHUD dismissWithSuccess:@"重启成功"];
                });
                
                [self.navigationController popViewControllerAnimated:YES];
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
}

//init changePasswordAlertView
- (UIView*)initializeAlertView:(UIView *)view
{
    view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 280, 133)];
    UILabel *changeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 280, 30)];
    changeLabel.text = @"修改密码";
    changeLabel.textAlignment = UITextAlignmentCenter;
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(37, 30, 56, 22)];
    nameLabel.text = @"旧密码:";
    UILabel *userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(37, 66, 56, 22)];
    userNameLabel.text = @"新密码:";
    UILabel *passwordLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 102, 73, 22)];
    passwordLabel.text = @"确认密码:";
    [view addSubview:nameLabel];
    [view addSubview:userNameLabel];
    [view addSubview:passwordLabel];
    [view addSubview:changeLabel];
    
    oldPasswordTextField = [[UITextField alloc] initWithFrame:CGRectMake(93, 30, 145, 22)];
    oldPasswordTextField.borderStyle = UITextBorderStyleBezel;
    oldPasswordTextField.delegate = self;
    newPasswordTextField = [[UITextField alloc] initWithFrame:CGRectMake(93, 66, 145, 22)];
    newPasswordTextField.borderStyle = UITextBorderStyleBezel;
    newPasswordTextField.delegate = self;
    surePasswordTextField = [[UITextField alloc] initWithFrame:CGRectMake(93, 102, 145, 22)];
    surePasswordTextField.borderStyle = UITextBorderStyleBezel;
    surePasswordTextField.delegate = self;
    [view addSubview:oldPasswordTextField];
    [view addSubview:newPasswordTextField];
    [view addSubview:surePasswordTextField];
    return view;
}

//changeDeviceName
-(UIView *)changeDeviceNameView:(UIView *)view
{
    view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 280, 133)];
    
    UILabel *connectlabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20,280 , 22)];
    connectlabel.text = @"修改名字";
    connectlabel.font = [UIFont systemFontOfSize:18];
    connectlabel.textAlignment = UITextAlignmentCenter;
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(27, 56, 56, 22)];
    nameLabel.text = @"旧名称:";
    UILabel *userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(27, 92, 83, 22)];
    userNameLabel.text = @"新名称:";
    [view addSubview:nameLabel];
    [view addSubview:connectlabel];
    [view addSubview:userNameLabel];

    UILabel *oldNameLbl = [[UILabel alloc] initWithFrame:CGRectMake(93, 56, 160, 22)];
    oldNameLbl.text = oldDeviceName;
    changeNameTextField = [[UITextField alloc] initWithFrame:CGRectMake(93, 92, 160, 22)];
    changeNameTextField.borderStyle = UITextBorderStyleBezel;
    changeNameTextField.delegate = self;
    [view addSubview:changeNameTextField];
    [view addSubview:oldNameLbl];
    
    return view;
}

-(UIView *)reSetView:(UIView *)view
{
    view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 280, 133)];
    
    UILabel *connectlabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20,280 , 22)];
    connectlabel.text = @"恢复出厂设置";
    connectlabel.textAlignment = UITextAlignmentCenter;
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(37, 56, 56, 22)];
    nameLabel.text = @"用户名:";
    UILabel *userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(54, 92, 73, 22)];
    userNameLabel.text = @"密码:";
    [view addSubview:nameLabel];
    [view addSubview:connectlabel];
    [view addSubview:userNameLabel];
    
    userNameTextField = [[UITextField alloc] initWithFrame:CGRectMake(93, 56, 145, 22)];
    userNameTextField.borderStyle = UITextBorderStyleBezel;
    userNameTextField.delegate = self;
    passWordTextField = [[UITextField alloc] initWithFrame:CGRectMake(93, 92, 145, 22)];
    passWordTextField.borderStyle = UITextBorderStyleBezel;
    passWordTextField.delegate = self;
    [view addSubview:userNameTextField];
    [view addSubview:passWordTextField];
    return view;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [oldPasswordTextField resignFirstResponder];
    [newPasswordTextField resignFirstResponder];
    [surePasswordTextField resignFirstResponder];
    [changeNameTextField resignFirstResponder];
    [userNameTextField resignFirstResponder];
    [passWordTextField resignFirstResponder];
    return YES;
}

-(void)textFiledEditChanged:(NSNotification *)obj{
    
    UITextField *textField = (UITextField *)obj.object;
    
    NSString *toBeString = textField.text;
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"])
    {
        // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position)
        {
            if (changeNameTextField.text.length > 8)
            {
                textField.text = [toBeString substringToIndex:8];
            }
        }
        // 有高亮选择的字符串，则暂不对文字进行统计和限制
        else
        {
        }
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else
    {
        if (toBeString.length > 8) {
            textField.text = [toBeString substringToIndex:8];
        }
    }
}

//- (NSInteger)lengthWithInRange:(NSRange)range replacementText:(NSString *)string with:(UITextField*)textField {
//    NSInteger textLength = 0;
//    UITextRange *selectedRange = [textField markedTextRange];
//    //获取高亮部分
//    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
//    
//    
//    if (!position) {
//        textLength = [textField.text length];
//    }
//    if (string.length > 0) {
//        //输入状态
//        NSString * newText = [textField textInRange:selectedRange];
//        
//        if (newText && [string length] > 1) {       //候选词替换高亮拼音时
//            
//            if (newText != nil) {
//                NSInteger tvLength = [textField.text length];
//                textLength += (tvLength-[newText length]);
//            }
//            
//            textLength += [string length];
//        }else {
//            if (newText != nil) {
//                NSInteger tvLength = [textField.text length];
//                textLength += (tvLength-[newText length]);
//            }
//            
//            textLength += 1;
//        }
//    }else {
//        //删除状态
//        if (textField.text.length > 0) {
//            NSString * newText = [textField textInRange:selectedRange];
//            if (newText != nil) {
//                NSInteger newLength = [newText length];
//                NSInteger tvLength = [textField.text length];
//                textLength += (tvLength-newLength);
//                if (newLength > 1) {
//                    textLength += 1;
//                }
//            }
//            else
//            {
//                textLength = [[textField.text substringToIndex:range.location] length];
//            }
//        }
//    }
//    
//    return textLength;
//}



#pragma mark - CustomIOS7Delegate
- (void)customIOS7dialogButtonTouchUpInside:(id)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //修改密码
    if([alertView tag] == 10000)
    {
        if (buttonIndex == 1)
        {
            [MMProgressHUD showWithTitle:@"修改密码中...."];
            if([newPasswordTextField.text isEqualToString:surePasswordTextField.text])
            {
                NSLog(@"oldPasswordTextField:%@ newPasswordTextField:%@,surePasswordTextField:%@ ",oldPasswordTextField.text,newPasswordTextField.text,surePasswordTextField.text);
                ipUrl = [Utitlity judgeipUrl];
                if (ipUrl)
                {
                     NSString *changPasswordStr = [NSString stringWithFormat:@"http://%@/cgi-bin/User.cgi?action=do_chpasswd&user=admin&passwd=%@&newpasswd=%@",ipUrl,oldPasswordTextField.text,surePasswordTextField.text];
                    
                    NSString * encodingString = [changPasswordStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                    NSLog(@"encodingString：%@",encodingString);
                    
                    [Utitlity commonHTTPMethod:encodingString responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
                        
                        NSLog(@"changePassword:%@",responseObject);
                        
                        if ([responseObject[@"state"] isEqualToString:@"Success"])
                        {
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                [MMProgressHUD dismissWithSuccess:@"修改密码成功"];
                            });
                        }
                    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                        NSLog(@"error:%@",error);
                    }];
                }
               
            }
            else
            {
                [MMProgressHUD dismissWithError:@"修改密码失败"];
            }
        }
    }
    else if([alertView tag] == 20000) //修改名称
    {
        if([changeNameTextField.text length] > 8)
        {
            changeNameTextField.text = [changeNameTextField.text substringToIndex:8];
        }
        
        NSLog(@"changeNameTextField:%@",changeNameTextField.text);
        if (buttonIndex == 1)
        {
            [MMProgressHUD showWithTitle:@"修改名称中...."];
            ipUrl = [Utitlity judgeipUrl];
            
            if ([changeNameTextField.text length] > 0 )
            {
                if (ipUrl)
                {
                    NSString *str = [NSString stringWithFormat:@"http://%@/cgi-bin/User.cgi?action=do_chdevname&oldname=%@&newname=%@",ipUrl,oldDeviceName,changeNameTextField.text];
                    
                    NSString * encodingString = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                    NSLog(@"encodingString：%@",encodingString);
                    
                    [Utitlity commonHTTPMethod:encodingString responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
                        
                        NSLog(@"changeName:%@",responseObject);
                        
                        if ([responseObject[@"state"] isEqualToString:@"Success"])
                        {
                            oldDeviceName = changeNameTextField.text;
                            [MMProgressHUD dismissWithSuccess:@"修改名称成功"];
                            
                            if (self.delegate) {
                                [self.delegate changeName:changeNameTextField.text];
                            }
                        }
                        
                    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                        NSLog(@"error:%@",error);
                    }];
                }
                else
                {
                    [MMProgressHUD dismissWithError:@"修改名称失败"];
                }
            }
            else
            {
                [MMProgressHUD dismissWithError:@"修改名称失败"];
            }
        }
    }
    else if ([alertView tag] == 40000)
    {
        if (buttonIndex == 1)
        {
            [MMProgressHUD showWithTitle:@"恢复出厂设置" status:@"恢复中....."];
            ipUrl = [Utitlity judgeipUrl];
            
            if (ipUrl)
            {
                NSString *resetStr = [NSString stringWithFormat:@"http://%@/cgi-bin/User.cgi?action=do_factory&user=%@&passwd=%@",ipUrl,userNameTextField.text,passWordTextField.text];
                NSString * encodingString = [resetStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                
                [Utitlity commonHTTPMethod:encodingString responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
                    NSLog(@"resetStr:%@",responseObject);
                    
                    if ([responseObject[@"state"] isEqualToString:@"Success"])
                    {
                        //子线程删除缓存
                        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                            NSString *uuidS = [[GlobalService sharedInstance].curOperationDeviceUUID stringByReplacingOccurrencesOfString:@":" withString:@""];
                            NSArray *array = [PersistableInfo findByCriteria:@"'%@%'",uuidS];
                            NSLog(@"array:%@",array);
                            
                            for (PersistableInfo *deleInfo in array)
                            {
                                NSString *uuid = deleInfo.uuid;
                                [PersistableInfo deleteByCriteria:@"where uuid = '%@'",uuid];
                            }
                            
                        });
                        
                        //同时断连设备
                        [MMProgressHUD dismissWithSuccess:@"恢复成功"];
                        
                        wis_user_dev device;
                        [value getValue:&device];
                        
                        if (self.delegate) {
                            [self.delegate unConnectDevice:device.uuid];
                        }
                        
                        [self.navigationController popViewControllerAnimated:YES];
                    }
                    else
                    {
                        [MMProgressHUD dismissWithError:@"输入账号密码错误"];
                    }
                    
                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    NSLog(@"error:%@",error);
                }];
            }
        }
        
    }
    
    [alertView close];
    
}

//#pragma mark- UIAlertViewDelegate
//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
//{
//    if (alertView.tag == 100)
//    {
//        [self.navigationController popToRootViewControllerAnimated:YES];
//    }
//    else if (alertView.tag == 200)
//    {
//        [self.navigationController popToRootViewControllerAnimated:YES];
//    }
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

//- (MBProgressHUD *)mbProgressHubWithT
//{
//     MBProgressHUD *progressHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
//    progressHUD.removeFromSuperViewOnHide = YES;
//    progressHUD.delegate = self;
//    progressHUD.labelText = @"Server Connecting...";
//    return progressHUD;
//}

@end
